package com.kmair.caiwu.dbconn.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.ExecutorType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import java.io.IOException;

@Configuration

@MapperScan(basePackages = "com.kmair.caiwu.*.dao")
@Import(DataSourceConfig.class)
public class MybatisConfig {
    @Bean
    public org.apache.ibatis.session.Configuration configuration() {
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
//        打开驼峰命名规则，将数据库A_COLUMN转行成JAVA的aColumn
        configuration.setMapUnderscoreToCamelCase(true);
//        这个配置使全局的映射器启用或禁用络缓存
        configuration.setCacheEnabled(true);
//        许JDBC支持生成的键，需要适合的驱动。如果设置为true，则这个设置强制生成的键被使用， 尽管一些驱动拒绝兼容但仍然有效（比如DERBY）
        configuration.setUseGeneratedKeys(true);
//        配置默认的执行器，SIMPLE执行器没有什么特别之处，REUSE执行器重用预处理语句。BATCH执行器重用 语句和批量更新
        configuration.setDefaultExecutorType(ExecutorType.REUSE);
//        全局启用或禁用延迟加载。当禁用时，所有关联对象都会即时加载
        configuration.setLazyLoadingEnabled(true);
//        设置超时时间，它决定驱动等待一个数据库响应的时间
        configuration.setDefaultStatementTimeout(3000);
        return configuration;
    }

    //配置sqlSessionFactory
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DruidDataSource dataSourceMySQL, org.apache.ibatis.session.Configuration configuration) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceMySQL);
        sqlSessionFactoryBean.setConfiguration(configuration);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/kmair/caiwu/*/resources/mapper/*.xml"));
        return sqlSessionFactoryBean;
    }

    //配置事务管理
    @Bean
    public DataSourceTransactionManager transactionManager(DruidDataSource dataSourceMySQL) {
        return new DataSourceTransactionManager(dataSourceMySQL);
    }
}
